﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using fbasync.web.Data;

namespace fbasync.web.Controls.TemplateEditor
{
    public partial class TemplateEditorMenu : System.Web.UI.UserControl
    {
        public const string ConfigFilePattern = "~/{0}.config";

        public static TemplateEditorMenu Instance
        {
            get { return (TemplateEditorMenu)HttpContext.Current.Items["TemplateEditorMenuInstance"]; }
            set { HttpContext.Current.Items["TemplateEditorMenuInstance"] = value; }
        }

        protected override void OnInit(EventArgs e)
        {
            Instance = this;

            base.OnInit(e);
        }

        protected override void OnPreRender(EventArgs e)
        {
            InitControls();

            base.OnPreRender(e);
        }

        public void InitControls()
        {
            uEditorMenuContainer.Visible = !TemplateEditorDataAccess.IsEditingMode();
            uiExportToConfigLink.NavigateUrl = String.Format(ConfigFilePattern, ApplicationManager.CurrentApplication.Name);
            uiExportAllToConfigLink.NavigateUrl = String.Format(ConfigFilePattern, Consts.DefaultConfigFileName);

            uiImportAppList.Items.Clear();

            foreach (ApplicationInfo appInfo in ApplicationManager.Applications)
            {
                if (ApplicationManager.CurrentApplication.Name.Equals(appInfo.Name)) continue;

                uiImportAppList.Items.Add(new ListItem(appInfo.Name, appInfo.FacebookApiKey));
            }
        }

        protected void AddTemplateBundleButton_Click(object sender, EventArgs e)
        {
            TemplateEditorDataAccess.CreateNewStoryTemplateBundle();

            ApplicationTemplates.Instance.ResetPager();
            ApplicationTemplates.Instance.InitControls();
        }

        protected void ImportLink_Click(object sender, EventArgs e)
        {
            TemplateEditorDataAccess.AsyncState asyncState = new TemplateEditorDataAccess.AsyncState();

            asyncState.Completed += new TemplateEditorDataAccess.AsyncCompleted(AsyncState_Completed);

            TemplateEditorDataAccess.ImportFromApplication(uiImportAppList.SelectedValue, asyncState);
        }

        private void AsyncState_Completed(TemplateEditorDataAccess.AsyncState sender)
        {
            if (null != ApplicationTemplates.Instance) ApplicationTemplates.Instance.BindTemplates();
            if (null != TemplateEditorMenu.Instance) TemplateEditorMenu.Instance.InitControls();

            if (!String.IsNullOrEmpty(sender.ErrorMessage)) ExceptionHandler.HandleException(new Exception(sender.ErrorMessage));
        }
    }
}